import gc,time,urequests,ujson
from userver import APP
from machine import Pin, reset
from unet import WIFI,AP
try:
    from config import version
except:
    version = (1,0)

# 初始化
HOST = "https://gitee.com/gushihui/mpy/raw/master/"
net = None
ssid = None
LED = Pin(2,Pin.OUT,value=0)
switch = Pin(15,Pin.OUT,value=1)
update_btn = Pin(4,Pin.IN,Pin.PULL_DOWN)

def blink():
    bt = 10
    while bt>0:
        LED.value(not LED.value())
        time.sleep_ms(200)
        bt -= 1
        
def free():
    gc.collect()

app = APP()
@app.router("/",method="GET")
def index():
    html = '''
    <h1>Welcome！</h1>
    <form action="/wifi" method="POST">
        <p>Password:<input type="password" name="pawd" id="pawd" /></p>
        <p><button type="submit">提交</button></p>
    </form>
    '''
    return html

@app.router("/wifi",method="POST")
def set_wifi():
    pawd = app.req.forms.get("pawd")
    print(pawd)
    
    with open("/wifi","w") as f:
        f.write(pawd)
        blink()
        print("Saved")
    
    reset()
    
def update_datetime():
    from machine import RTC

    rtc = RTC()
    year = rtc.datetime()[0]
    if year==2000:
        try:
            json_text = urequests.get("http://quan.suning.com/getSysTime.do").json()['sysTime2']
            time_list = [int(x) for x in json_text.replace("-"," ").replace(":"," ").split(" ")]
            rtc_format = (time_list[0],time_list[1],time_list[2],0,time_list[3],time_list[4],time_list[5],0)
            rtc.datetime(rtc_format)
            return 201
        except:
            return 400
    else:
        return 200

def backup(fromPath,toPath="/bak"):
    with open(fromPath) as fromFile:
        with open(toPath+"/"+fromPath, 'w') as toFile:
            CHUNK_SIZE = 512 # bytes
            data = fromFile.read(CHUNK_SIZE)
            while data:
                toFile.write(data)
                data = fromFile.read(CHUNK_SIZE)

def update_file():
    try:
        # 对比config版本，如果本地低于网络版本，更新本地版本
        configs = urequests.get(HOST + "update.json").json()
    
        if version < tuple(configs['version']):
            print("Updating...")
                    
            files = configs.get("files")
            if files:
                print("loading files")
                for file in files:
                    backup(file)
                    free()
                    file_content = urequests.get(HOST + file).text
                    with open(file,"w") as f:
                        f.write(file_content)
                    del file_content
                    free()      
                del configs['files']
                reset()
        else:
            print("is new")
    except:
        print("error")

def init():
    net = WIFI()
    time.sleep(10)
    ssid = net.get_wifi_list()[0]
    if net.linked:
        print("Linked")
        blink()
        free()
        return True
    else:
        try:            
            with open("/wifi","r") as f:
                print("config.json 存在,开始读取")
                pawd = f.read()
                print("Password:",pawd)
                
                print("WIFI ID:",ssid)
                net.connect(ssid,pawd)
                time.sleep(15)
                if net.linked:
                    print("loaded and login")
                    return True
                else:
                    print("登录不成功")
        except:
            print("文件不存在")        
            if ssid:
                print("start AP")
                net = AP()
                print("AP IP:",net.get_ip())
                app.run()
            return

islinked = init()
if islinked:
    update_datetime()
    update_btn.irq(handler=update_file,trigger=Pin.IRQ_RISING) # 定义中断，上升沿触发update_file()
    
del AP
app = None
del app
del blink
del update_datetime
del init
free()